package com.translation.verb;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.translation.dao.BaseDAO;

public class VerbImporter {

	private BaseDAO dao = new BaseDAO();

	private void batch(String fname, IteratorBatch<String> batch) throws IOException, SQLException {

		BufferedReader r = null;
		try {
			r = new BufferedReader(new FileReader(fname));
			final BufferedReader r1 = r;
			Iterator<String> it = new Iterator<String>() {

				Pattern p = Pattern.compile("([^\\p{Punct}\\s\\d]([-']|[^\\p{Punct}\\s])*)");
				Matcher m = null;

				@Override
				public void remove() {
				}

				@Override
				public String next() {
					String word = null;
					try {
						String line;
						if (m != null) {
							if (m.find()) {
								word = m.group(1).trim();
								if (word.length() > 255) {
									word = null;
								}
							} else {
								m = null;
							}
						}
						while (word == null && (line = r1.readLine()) != null) {
							m = p.matcher(line);
							if (m.find()) {
								word = m.group(1).trim();
								if (word.length() > 255) {
									word = null;
								}
							}
						}
					} catch (Exception e) {
					}
					return word;
				}

				@Override
				public boolean hasNext() {
					return true;
				}
			};

			/*
			String str = "";
			while ((str = it.next()) != null) {
				System.out.println(str.toLowerCase());
			}
			 */

			batch.setIterator(it);
			dao.namedBatch("verb", batch);
		} finally {
			if (r != null) {
				r.close();
			}
		}
	};

	public static void main(String[] args) throws IOException, SQLException {
		VerbImporter i = new VerbImporter();
		i.batches(args[0], args[1]);
	}

	private void batches(String fname, String locale) throws IOException, SQLException {
		BatchFactory f = BatchFactory.getInstance(locale);

		List<? extends IteratorBatch<String>> batches = f.getBatches();

		for (IteratorBatch<String> batch : batches) {
			this.batch(fname, batch);
		}
	}

}
